package com.ruoyi.cms.schedule;

import com.ruoyi.cms.post.service.ICmsPostService;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

import static com.ruoyi.common.constant.RedisConstants.POST_ID_KEY;
import static com.ruoyi.common.constant.RedisConstants.PREFIX;

/**
 * 定时任务
 * @author toumakazusa
 * @since 1.0.0
 */
@Component("cmsSchedule")
public class MySchedule {

    @Autowired
    private RedisTemplate stringRedisTemplate;

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    @Autowired
    private ICmsPostService postService;

    @Scheduled(cron = "0 0 2 * * ?") // 每天2:00更新
    public void scheduledUpdatePageview() {
        log.info("检查是否更新帖子");
        Set<String> keys = stringRedisTemplate.keys(PREFIX + POST_ID_KEY + "*");
        for (String key : keys) {
            // 获取文章id
            String postId = key.substring(PREFIX.length() + POST_ID_KEY.length());
            log.error("更新帖子：{}", postId);
            // 获取帖子浏览量
            Long size = stringRedisTemplate.opsForHyperLogLog().size(key);
            // 更新成功删除key
            if (postService.updatePostPageview(postId, size) == 1) {
                stringRedisTemplate.delete(key);
                stringRedisTemplate.delete(key.substring(PREFIX.length()));
            }
        }
    }
}
